package com.ks.xcamera.view;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.king.camera.scan.CameraScan;
import com.ks.basictools.base.BaseActivity;
import com.ks.basictools.manager.ActivityManager;
import com.ks.basictools.provider.ContextGlobal;
import com.ks.basictools.utils.ToastUtils;
import com.ks.xcamera.Interface.OnCustomCityPickerItemClickListener;
import com.ks.xcamera.R;
import com.ks.xcamera.adapter.GridImageAdapter;
import com.ks.xcamera.constant.Constants;
import com.ks.xcamera.databinding.ActivityMainBinding;
import com.ks.xcamera.manager.FullyGridLayoutManager;
import com.ks.xcamera.manager.GlideEngine;
import com.ks.xcamera.manager.ListDataManager;
import com.ks.xcamera.manager.PreferenceManager;
import com.ks.xcamera.responseBean.CustomCityData;
import com.ks.xcamera.responseBean.UploadBean;
import com.ks.xcamera.utils.NetworkUtils;
import com.ks.xcamera.wedget.picker.CustomCityPicker;
import com.ks.xcamera.wedget.picker.CustomConfig;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.language.LanguageConfig;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.utils.DensityUtil;
import com.luck.picture.lib.utils.MediaUtils;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.mingle.widget.ShapeLoadingDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.callback.UIProgressResponseCallBack;
import com.xuexiang.xhttp2.exception.ApiException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

public class MainActivity extends BaseActivity {
    private final String TAG = MainActivity.class.getSimpleName();

    private ActivityMainBinding mBinding;

    private CustomCityPicker threePicker, storePicker, kuaiDiPicker;
    private String express_num/*快递单号*/, express_company/*快递公司*/, shop_name/*店铺*/, damage_desc/*损坏描述*/, spec/*规格*/, productNum/*产品数量*/;
    private GridImageAdapter mAdapter;
    private final List<LocalMedia> mData = new ArrayList<>();

    private GlideEngine imageEngine;
    private PictureSelectorStyle selectorStyle;
    private ShapeLoadingDialog shapeLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar(true, true, R.color.colorTrans);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setActivity(this);
        start(savedInstanceState);
    }

    private void start(Bundle savedInstanceState) {
        String code = getIntent().getStringExtra(CameraScan.SCAN_RESULT);
        express_num = code;
        mBinding.tvNumber.setText(code);
        initObject(savedInstanceState);
    }

    private void initObject(Bundle savedInstanceState) {
        threePicker = new CustomCityPicker(this);
        storePicker = new CustomCityPicker(this);
        kuaiDiPicker = new CustomCityPicker(this);

        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                4, GridLayoutManager.VERTICAL, false);
        mBinding.recycler.setLayoutManager(manager);
        RecyclerView.ItemAnimator itemAnimator = mBinding.recycler.getItemAnimator();
        if (itemAnimator != null) {
            ((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
        }
        mBinding.recycler.addItemDecoration(new GridSpacingItemDecoration(4,
                DensityUtil.dip2px(this, 8), false));
        mAdapter = new GridImageAdapter(this, mData);
        // 设置最大选择数量
        mAdapter.setSelectMax(2);
        mBinding.recycler.setAdapter(mAdapter);
        if (savedInstanceState != null && savedInstanceState.getParcelableArrayList("selectorList") != null) {
            mData.clear();
            mData.addAll(savedInstanceState.getParcelableArrayList("selectorList"));
        }
        imageEngine = GlideEngine.createGlideEngine();
        selectorStyle = new PictureSelectorStyle();
        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                // 预览图片、视频、音频
                PictureSelector.create(MainActivity.this)
                        .openPreview()
                        .setImageEngine(imageEngine)
                        .setSelectorUIStyle(selectorStyle)
                        .setLanguage(LanguageConfig.CHINESE)
                        .isPreviewFullScreenMode(true)
                        .isPreviewZoomEffect(true, mBinding.recycler)
                        .setExternalPreviewEventListener(new MyExternalPreviewEventListener())
                        .startActivityPreview(position, true, mAdapter.getData());
            }

            @Override
            public void openPicture() {
                // 拍照
                PictureSelector.create(MainActivity.this)
                        .openCamera(SelectMimeType.ofImage())
                        .setSelectedData(mAdapter.getData())
                        .setCompressEngine((CompressFileEngine) (context, source, call)
                                -> Luban.with(context).load(source).ignoreBy(100)
                                .setCompressListener(new OnNewCompressListener() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onSuccess(String source, File compressFile) {
                                        if (call != null) {
                                            call.onCallback(source, compressFile.getAbsolutePath());
                                        }
                                    }

                                    @Override
                                    public void onError(String source, Throwable e) {
                                        if (call != null) {
                                            call.onCallback(source, null);
                                        }
                                    }
                                }).launch())
                        .forResult(new MeOnResultCallbackListener());
            }
        });
    }

    /**
     * 外部预览监听事件
     */
    private class MyExternalPreviewEventListener implements OnExternalPreviewEventListener {

        @Override
        public void onPreviewDelete(int position) {
            mAdapter.remove(position);
            mAdapter.notifyItemRemoved(position);
        }

        @Override
        public boolean onLongPressDownload(Context context, LocalMedia media) {
            return false;
        }
    }

    private class MeOnResultCallbackListener implements OnResultCallbackListener<LocalMedia> {
        @Override
        public void onResult(ArrayList<LocalMedia> result) {
            analyticalSelectResults(result);
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "PictureSelector Cancel");
        }
    }

    /**
     * 处理选择结果
     */
    private void analyticalSelectResults(ArrayList<LocalMedia> result) {
        for (LocalMedia media : result) {
            if (media.getWidth() == 0 || media.getHeight() == 0) {
                if (PictureMimeType.isHasImage(media.getMimeType())) {
                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(this, media.getPath());
                    media.setWidth(imageExtraInfo.getWidth());
                    media.setHeight(imageExtraInfo.getHeight());
                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(this, media.getPath());
                    media.setWidth(videoExtraInfo.getWidth());
                    media.setHeight(videoExtraInfo.getHeight());
                }
            }
            Log.i(TAG, "文件名: " + media.getFileName());
            Log.i(TAG, "是否压缩:" + media.isCompressed());
            Log.i(TAG, "压缩路径:" + media.getCompressPath());
            Log.i(TAG, "初始路径:" + media.getPath());
            Log.i(TAG, "绝对路径:" + media.getRealPath());
            Log.i(TAG, "是否裁剪:" + media.isCut());
            Log.i(TAG, "裁剪路径:" + media.getCutPath());
            Log.i(TAG, "是否开启原图:" + media.isOriginal());
            Log.i(TAG, "原图路径:" + media.getOriginalPath());
            Log.i(TAG, "沙盒路径:" + media.getSandboxPath());
            Log.i(TAG, "水印路径:" + media.getWatermarkPath());
            Log.i(TAG, "视频缩略图:" + media.getVideoThumbnailPath());
            Log.i(TAG, "原始宽高: " + media.getWidth() + "x" + media.getHeight());
            Log.i(TAG, "裁剪宽高: " + media.getCropImageWidth() + "x" + media.getCropImageHeight());
            Log.i(TAG, "文件大小: " + PictureFileUtils.formatAccurateUnitFileSize(media.getSize()));
            Log.i(TAG, "文件时长: " + media.getDuration());
        }
        runOnUiThread(() -> {
            boolean isMaxSize = result.size() == mAdapter.getSelectMax();
            int oldSize = mAdapter.getData().size();
            mAdapter.notifyItemRangeRemoved(0, isMaxSize ? oldSize + 1 : oldSize);
            mAdapter.getData().clear();

            mAdapter.getData().addAll(result);
            mAdapter.notifyItemRangeInserted(0, result.size());
        });
    }


    public void onClick_storePicker(View ignoreV) {
        if (ListDataManager.getInstance().getStoreDataList().isEmpty()) {
            ToastUtils.show(this, "正在获取数据。。。");
            ListDataManager.getInstance().requestData();
            return;
        }
        CustomConfig cityConfig = new CustomConfig.Builder()
                .title("选择店铺名称")
                .visibleItemsCount(5)
                .setCityData(ListDataManager.getInstance().getStoreDataList())
                .provinceCyclic(false)
                .cityCyclic(false)
                .setCustomItemLayout(R.layout.item_custome_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_custome_city_name_tv)
                .titleBackgroundColor("#ffffff")
                .titleTextColor("#333333")
                .titleTextSize(24)
                .cancelTextColor("#AAAAAA")
                .cancelTextSize(24)
                .confirmTextSize(24)
                .confirTextColor("#357CFF")
                .districtCyclic(false)
                .drawShadows(true)
                .setCityWheelType(CustomConfig.WheelType.PRO)
                .build();

        storePicker.setCustomConfig(cityConfig);
        storePicker.setOnCustomCityPickerItemClickListener(new OnCustomCityPickerItemClickListener() {
            @Override
            public void onSelected(CustomCityData province, CustomCityData city, CustomCityData district) {
                if (province != null && city != null && district != null) {
                    shop_name = province.getName();
                    mBinding.tvStore.setText(province.getName());
                } else {
                    mBinding.tvStore.setText("选择店铺名称");
                }
            }
        });
        storePicker.showCityPicker();
    }

    public void onClick_kuaiDiPicker(View ignoreV) {
        if (ListDataManager.getInstance().getKuaiDiDataList().isEmpty()) {
            ToastUtils.show(this, "正在获取数据。。。");
            ListDataManager.getInstance().requestData();
            return;
        }
        CustomConfig cityConfig = new CustomConfig.Builder()
                .title("选择快递公司")
                .visibleItemsCount(5)
                .setCityData(ListDataManager.getInstance().getKuaiDiDataList())
                .provinceCyclic(false)
                .cityCyclic(false)
                .setCustomItemLayout(R.layout.item_custome_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_custome_city_name_tv)
                .districtCyclic(false)
                .drawShadows(true)
                .titleBackgroundColor("#ffffff")
                .titleTextColor("#333333")
                .titleTextSize(24)
                .cancelTextColor("#AAAAAA")
                .cancelTextSize(24)
                .confirmTextSize(24)
                .confirTextColor("#357CFF")
                .setCityWheelType(CustomConfig.WheelType.PRO)
                .build();

        kuaiDiPicker.setCustomConfig(cityConfig);
        kuaiDiPicker.setOnCustomCityPickerItemClickListener(new OnCustomCityPickerItemClickListener() {
            @Override
            public void onSelected(CustomCityData province, CustomCityData city, CustomCityData district) {
                if (province != null && city != null && district != null) {
                    express_company = province.getName();
                    mBinding.tvKuaidi.setText(province.getName());
                } else {
                    mBinding.tvKuaidi.setText("选择快递公司");
                }
            }
        });
        kuaiDiPicker.showCityPicker();
    }

    public void onClick_threePicker(View ignoreV) {
        if (ListDataManager.getInstance().getThreeDataList().isEmpty()) {
            ToastUtils.show(this, "正在获取数据。。。");
            ListDataManager.getInstance().requestData();
            return;
        }
        CustomConfig cityConfig = new CustomConfig.Builder()
                .title("选择产品规格")
                .visibleItemsCount(10)
                .setCityData(ListDataManager.getInstance().getThreeDataList())
                .provinceCyclic(false)
                .cityCyclic(false)
                .setCustomItemLayout(R.layout.item_custome_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_custome_city_name_tv)
                .titleBackgroundColor("#ffffff")
                .titleTextColor("#333333")
                .titleTextSize(24)
                .cancelTextColor("#AAAAAA")
                .cancelTextSize(24)
                .confirmTextSize(24)
                .confirTextColor("#357CFF")
                .districtCyclic(false)
                .drawShadows(true)
                .setCityWheelType(CustomConfig.WheelType.PRO_CITY_DIS)
                .build();

        threePicker.setCustomConfig(cityConfig);
        threePicker.setOnCustomCityPickerItemClickListener(new OnCustomCityPickerItemClickListener() {
            @Override
            public void onSelected(CustomCityData province, CustomCityData city, CustomCityData district) {
                if (province != null && city != null && district != null) {
                    String text = province.getName() + "/" + city.getName() + "/" + district.getName();
                    spec = text;
                    mBinding.tvThree.setText(text);
                } else {
                    mBinding.tvThree.setText("选择产品规格");
                }
            }
        });
        threePicker.showCityPicker();
    }

    public void onClick_finish(View ignoreV) {
        ActivityManager.getInstance().finishActivity();
    }

    public void onClick_upload(View ignoreV) {
        urls.delete(0, urls.length());
        ArrayList<LocalMedia> data = mAdapter.getData();
        for (LocalMedia media : data) {
            File file = new File(media.getCompressPath());
            upload(file);
        }
    }

    private final StringBuffer urls = new StringBuffer();

    private void upload(File file) {
        Map<String, Object> param = new HashMap<>();
        param.put("token", PreferenceManager.getInstance().getToken(ContextGlobal.get().getContext()));
        XHttp.post(Constants.URL_UPLOAD)
                .params(param)
                .uploadFile("file", file, new UIProgressResponseCallBack() {
                    @Override
                    public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                        Log.d("zhxk", "文件上传进度: bytesRead = " + bytesRead
                                + " contentLength = " + contentLength
                                + "  done = " + done);
                    }
                })
                .execute(new SimpleCallBack<UploadBean>() {

                    @Override
                    public void onSuccess(UploadBean bean) {
                        Log.d("zhxk", "onSuccess: url = " + bean.getUrl());
                        urls.append(bean.getUrl()).append(",");

                        String[] split = urls.toString().split(",");
                        Log.d("zhxk", "split.length = " + split.length
                                + " mAdapter.getData().size() = " + mAdapter.getData().size());
                        if (split.length == mAdapter.getData().size()) {
                            executeCommit();
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissLoadingDialog();
                        ToastUtils.show(MainActivity.this, e.getMessage());
                        e.printStackTrace();
                    }
                });
    }

    public void onClick_commit(View ignoreV) {
        damage_desc = mBinding.etRemark.getText().toString();
        productNum = mBinding.etProductNum.getText().toString();
        if (TextUtils.isEmpty(express_num)
                || TextUtils.isEmpty(express_company)
                || TextUtils.isEmpty(shop_name)
//                || TextUtils.isEmpty(damage_desc)
                || TextUtils.isEmpty(spec)) {
            ToastUtils.show(this, "请选择数据");
            return;
        }

        boolean networkConnected = NetworkUtils.isNetworkConnected(this);
        if (!networkConnected) {
            ToastUtils.show(this, "网络不给力，请检查网络设置");
            return;
        }

        showLoadingDialog();
        if (mAdapter.getData().isEmpty()) {
            executeCommit();
        } else {
            onClick_upload(null);
        }
    }

    private void executeCommit() {
        Map<String, Object> param = new HashMap<>();
        param.put("token", PreferenceManager.getInstance().getToken(ContextGlobal.get().getContext()));
        param.put("express_num", express_num);
        param.put("express_company", express_company);
        param.put("shop_name", shop_name);
        param.put("damage_desc", damage_desc);
        param.put("goods_num", productNum);
        param.put("spec", spec);
        param.put("images", urls.toString());
        XHttp.post(Constants.URL_INSERT_INFO)
                .params(param)
                .onMainThread(false)
                .execute(new SimpleCallBack<Object>() {

                    @Override
                    public void onSuccess(Object bean) {
                        runOnUiThread(() -> {
                            dismissLoadingDialog();
                            ToastUtils.show(ContextGlobal.get().getContext(), "录入成功，2s后返回");
                            new Handler().postDelayed(() -> ActivityManager.getInstance().finishActivity(), 2000);
                        });
                    }

                    @Override
                    public void onError(ApiException e) {
                        runOnUiThread(() -> {
                            dismissLoadingDialog();
                            if (e != null) {
                                if (e.getCode() == 300 && e.getDisplayMessage().equals("Multiple Choices")) {
                                    ToastUtils.show(ContextGlobal.get().getContext(), "该商品已被录入");
                                } else {
                                    ToastUtils.show(ContextGlobal.get().getContext(), e.getDisplayMessage());
                                }
                            } else {
                                ToastUtils.show(ContextGlobal.get().getContext(), "未知错误");
                            }
                        });
                    }
                });
    }

    private void showLoadingDialog() {
        if (shapeLoadingDialog == null) {
            shapeLoadingDialog = new ShapeLoadingDialog(this);
            shapeLoadingDialog.setCanceledOnTouchOutside(false);
        }
        shapeLoadingDialog.show();
    }

    private void dismissLoadingDialog() {
        if (shapeLoadingDialog != null) {
            shapeLoadingDialog.dismiss();
        }
    }
}